package com.sf.ams.utils;

import java.io.File;
import java.io.IOException;

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sf.ams.constant.Constant;
import com.sf.ams.entity.SystemInfo;

/**
 * 描述：
 * 
 * <pre>HISTORY
 * ****************************************************************************
 *  ID   DATE           PERSON          REASON
 *  1    2017年9月27日      Simba.Hua         Create
 * ****************************************************************************
 * </pre>
 * @author Simba.Hua
 */
public class GitUtil {
	private static Logger logger = LoggerFactory.getLogger(GitUtil.class);
	public static boolean pullBranchToLocal(SystemInfo system){
		String thisSystemDir = Constant.LOCAL_CODE_DIR + Constant.PATH_SPLIT_CHARACTOR + system.getSystemCode() + Constant.PATH_SPLIT_CHARACTOR + Constant.GIT_SQL_PATH;
        boolean resultFlag = false;
        //检查目标文件夹是否存在
        File gitfile =  new File(thisSystemDir + Constant.PATH_SPLIT_CHARACTOR + ".git");
       
        try {
        	CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(system.getGitUserName(),AESUtil.AESDncode(system.getSystemCode(), system.getGitPassword()));
        	
        	 if(gitfile.exists()){
        		 logger.info("system {}'s code exists,will pull code from git!",system.getSystemCode());
        		 Git.open(gitfile).pull().setCredentialsProvider(credentialsProvider).setRemoteBranchName(system.getGitBranch()).call();
             }else{
            	 logger.info("system {}'s code not exists,will clone code from git!",system.getSystemCode());
            	 Git.cloneRepository().setURI(system.getPathAddress()).setDirectory(new File(thisSystemDir))
            	 .setCredentialsProvider(credentialsProvider).setBranch(system.getGitBranch()).call();
             }
			resultFlag = true;
        } 
        catch (GitAPIException e) {
        	logger.error("system {} clone or pull code from git error",system.getSystemCode(),e);
        } 
        catch (IOException e) {
        	logger.error("system {} clone code from git error",system.getSystemCode(),e);
		}
        return resultFlag;    
    }
}
